<template>
  <div class="container-publish">
    <el-card>
      <div slot="header">
        <!-- 自己封装的组件实现 -->
        <my-bread>{{$route.query.id?'修改文章':'发布文章'}}</my-bread>
      </div>
      <!-- 表单 -->
      <el-form ref="articleForm" :model="articleForm" :rules="articeRules" label-width="120px">
        <el-form-item label="标题:" prop="title">
          <!-- 标题 :输入框 -->
          <el-input placeholder="请输入文章标题" style="width:200px" v-model="articleForm.title"></el-input>
        </el-form-item>
        <!-- 富文本 -->
        <el-form-item label="内容：" prop="content">
          <!-- trigger:blur 无法监听富文本失去焦点去进行校验 -->
          <!-- 自己绑定富文本的失去焦点事件，在事件处理函数中对改字段进行校验即可 -->
          <quill-editor
            @blur="checkContent()"
            v-model="articleForm.content"
            :options="editorOption"
          />
        </el-form-item>
        <!-- 封面 -->
        <el-form-item label="封面:" prop="cover.type">
          <el-radio-group @change="articleForm.cover.images=[]" v-model="articleForm.cover.type">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>
          <div style="magin-top=10px" v-if="articleForm.cover.type===1">
            <my-image @confirm="checkCover()" v-model="articleForm.cover.images[0]"></my-image>
          </div>
          <div style="magin-top=10px" v-if="articleForm.cover.type===3">
            <my-image
              v-for="i in 3"
              :key="i"
              @confirm="checkCover()"
              v-model="articleForm.cover.images[i-1]"
            ></my-image>
          </div>
        </el-form-item>
        <!-- 频道 -->
        <el-form-item label="频道" prop="channel_id">
          <my-channel v-model="articleForm.channel_id"></my-channel>
        </el-form-item>
        <el-form-item v-if="$route.query.id">
          <el-button type="success" @click="editArticle()">修改文章</el-button>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item v-else>
          <el-button @click="saveArticle(false)" type="primary">发布文章</el-button>
          <el-button @click="saveArticle(true)">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import { quillEditor } from "vue-quill-editor";
export default {
  name: "page-publish",

  components: {
    quillEditor,
  },
  data() {
    const validCoverFn = (rules, value, callback) => {
      const images = this.articleForm.cover.images;
      //value = cover.type
      if (value === 1) {
        //单图校验逻辑
        if (images[0] && images.length === 1) {
          callback();
        } else {
          callback(new Error("请选择一张图"));
        }
      } else if (value === 3) {
        if (images[0] && images[1] && images[2]) {
          callback();
        } else {
          callback(new Error("请选择三张图"));
        }
      } else {
        callback();
      }
    };
    return {
      //文章表单数据
      articleForm: {
        title: null,
        channel_id: null,
        content: null,
        cover: {
          type: 1,
          images: [],
        },
      },
      articeRules: {
        title: [
          { required: true, message: "请输入标题名称", trigger: "blur" },
          { min: 5, max: 30, message: "请输入5-30字符", trigger: "blur" },
        ],
        content: [
          { required: true, message: "请输入文章内容", trigger: "blur" },
        ],
        channel_id: [
          { required: true, message: "请输入文章频道", trigger: "change" },
        ],
        "cover.type": [{ validator: validCoverFn, trigger: "change" }],
      },
      //富文本配置对象
      editorOption: {
        placeholder: "请输入文章内容",
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"],
            ["blockquote", "code-block"],
            [{ header: 1 }, { header: 2 }],
            [{ list: "ordered" }, { list: "bullet" }],
            [{ indent: "-1" }, { indent: "+1" }],
            ["image"],
          ],
        },
      },
    };
  },
  created() {
    //刷新页面就判断是否有id
    if (this.$route.query.id) {
      this.getArticle();
    }
  },
  watch: {
    //监听地址栏
    "$route.query.id": function () {
      if ($route.query.id) {
        //修改文章+填充表单
        this.getArticle();
      } else {
        //发表文章+重置表单
        this.$refs.articleForm.resetFields();
      }
    },
  },

  methods: {
    editArticle() {
      // 进行表单的整体校验
      this.$refs.articleForm.validate(async (valid) => {
        //判断valid表单的全部数据
        if (valid) {
          try {
            await this.$http.put(
              `articles/${this.$route.query.id}`,
              this.articleForm
            );
            this.$message.success("修改成功");
            this.$router.push("/article");
          } catch (e) {
            this.$message.error("修改失败");
          }
        }
      });
    },
    //获取表单数据+填充数据
    async getArticle() {
      const res = await this.$http.get(`articles/${this.$route.query.id}`);
      this.articleForm = res.data.data;
    },
    //表单验证 y添加文章
    saveArticle(draft) {
      // 整体表单校验
      this.$refs.articleForm.validate(async (valid) => {
        if (valid) {
          try {
            // 进行添加请求
            await this.$http.post(`articles?draft=${draft}`, this.articleForm);
            // 成功提示
            this.$message.success(draft ? "存入草稿成功" : "发布文章成功");
            // 跳转内容管理
            this.$router.push("/article");
          } catch (e) {
            // 失败提示
            this.$message.error(draft ? "存入草稿失败" : "发布文章失败");
          }
        }
      });
    },
    checkCover() {
      //触发cover.type 校验规则,去校验封面图的数据
      this.$refs.articleForm.validateField("cover.type");
    },
    checkContent() {
      this.$refs.articleForm.validateField("content");
    },
  },
};
</script>

<style lang='less' scoped>
//::v-deep是深度作用符号 让选择器在其他组件下生效
.container-publish ::v-deep .quill-editor {
  height: 250px;
  margin-bottom: 40px;
}
::v-deep .ql-toolbar.ql-snow {
  padding: 0 8px;
}
</style>